<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\MoneyTransaction;
use App\Models\MoneyBook;
use App\Models\MoneyCategory;
use Carbon\Carbon;

class HomeController extends Controller
{
    /**
     * 显示首页
     */
    public function index()
    {
        $user = Auth::user();

        // 获取用户的默认账本
        $moneyBook = $user->getCurrentDefaultBook();

        // 如果没有账本，创建默认账本
        if (!$moneyBook) {
            $moneyBook = MoneyBook::create([
                'name' => '默认账本',
                'description' => '系统自动创建的默认账本',
                'user_id' => $user->id,
            ]);

            // 设置为默认账本
            $user->update(['default_book_id' => $moneyBook->id]);
        }

        // 获取当前月份的开始和结束时间
        $startOfMonth = Carbon::now()->startOfMonth();
        $endOfMonth = Carbon::now()->endOfMonth();

        // 计算当前余额（所有收入 - 所有支出）
//        $totalIncome = MoneyTransaction::where('book_id', $moneyBook->id)
//            ->where('type', MoneyCategory::TYPE_INCOME)
//            ->sum('amount');
//        $totalExpense = MoneyTransaction::where('book_id', $moneyBook->id)
//            ->where('type', MoneyCategory::TYPE_EXPENSE)
//            ->sum('amount');
//        $currentBalance = $totalIncome - $totalExpense;

        // 计算本月收入和支出
        $monthlyIncome = MoneyTransaction::where('book_id', $moneyBook->id)
            ->where('type', MoneyCategory::TYPE_INCOME)
            ->whereBetween('transaction_date', [$startOfMonth, $endOfMonth])
            ->sum('amount');

        $monthlyExpense = MoneyTransaction::where('book_id', $moneyBook->id)
            ->where('type', MoneyCategory::TYPE_EXPENSE)
            ->whereBetween('transaction_date', [$startOfMonth, $endOfMonth])
            ->sum('amount');
        $currentBalance = $monthlyIncome - $monthlyExpense;

        // 获取最近的交易记录（最多5条）
        $recentTransactions = MoneyTransaction::where('book_id', $moneyBook->id)
            ->with(['category', 'subCategory', 'user'])
            ->orderBy('transaction_date', 'desc')
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get();

        // 格式化交易数据
        $formattedTransactions = $recentTransactions->map(function($transaction) {
            return [
                'id' => $transaction->id,
                'type' => $transaction->type == MoneyCategory::TYPE_INCOME ? 'income' : 'expense',
                'amount' => $transaction->amount,
                'description' => $transaction->description,
                'category' => $transaction->category->name ?? '未分类',
                'sub_category' => $transaction->subCategory->name ?? '',
                'user_name' => $transaction->user->name ?? '未知用户',
                'user_avatar_url' => $transaction->user->avatar_url,
                'date' => $transaction->transaction_date,
                'icon' => $transaction->subCategory ? $transaction->subCategory->icon : $transaction->category->icon,
            ];
        });

        return view('home.index', [
            'title' => '首页',
            'currentBalance' => $currentBalance,
            'monthlyIncome' => $monthlyIncome,
            'monthlyExpense' => $monthlyExpense,
            'recentTransactions' => $formattedTransactions,
            'userName' => $user->name,
        ]);
    }

    /**
     * 根据分类名称获取对应的图标
     */
    private function getCategoryIcon($categoryName)
    {
        $icons = [
            '餐饮' => '🍔',
            '交通' => '🚇',
            '购物' => '🛒',
            '娱乐' => '🎮',
            '医疗' => '🏥',
            '教育' => '📚',
            '住房' => '🏠',
            '通讯' => '📱',
            '工资' => '💰',
            '奖金' => '🎁',
            '投资' => '📈',
            '其他收入' => '💵',
            '其他支出' => '💸',
            '其他' => '📝',
        ];

        return $icons[$categoryName] ?? '📝';
    }

    /**
     * 获取用户统计数据（AJAX接口）
     */
    public function getStats(Request $request)
    {
        try {
            $user = Auth::user();

            // 获取用户的默认账本
            $moneyBook = $user->getCurrentDefaultBook();

            if (!$moneyBook) {
                return response()->json([
                    'success' => false,
                    'message' => '未找到账本数据'
                ]);
            }

            // 获取指定月份的数据（默认当前月）
            $month = $request->get('month', Carbon::now()->format('Y-m'));
            $startOfMonth = Carbon::createFromFormat('Y-m', $month)->startOfMonth();
            $endOfMonth = Carbon::createFromFormat('Y-m', $month)->endOfMonth();

            // 计算统计数据
            $monthlyIncome = MoneyTransaction::where('book_id', $moneyBook->id)
                ->where('type', MoneyCategory::TYPE_INCOME)
                ->whereBetween('transaction_date', [$startOfMonth, $endOfMonth])
                ->sum('amount');

            $monthlyExpense = MoneyTransaction::where('book_id', $moneyBook->id)
                ->where('type', MoneyCategory::TYPE_EXPENSE)
                ->whereBetween('transaction_date', [$startOfMonth, $endOfMonth])
                ->sum('amount');

            return response()->json([
                'success' => true,
                'data' => [
                    'monthly_income' => $monthlyIncome,
                    'monthly_expense' => $monthlyExpense,
                    'net_income' => $monthlyIncome - $monthlyExpense,
                    'month' => $month,
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '获取统计数据失败'
            ], 500);
        }
    }
}
